Searching the DOM
In this tutorial, we will learn how to search for elements in the DOM using JavaScript. In JavaScript, there are multiple ways to get elements from the DOM. Here’s a comprehensive list of all the methods used to retrieve elements:
1. Selecting Elements by ID
Method document.getElementById(id)
Description Selects a single element by its ID.
Example let element = document.getElementById("myId");
2. Selecting Elements by Class Name
Method document.getElementsByClassName(className)
Description Selects all elements with a specific class (returns an HTMLCollection).
Example let elements = document.getElementsByClassName("myClass");
3. Selecting Elements by Tag Name
Method document.getElementsByTagName(tagName)
Description Selects all elements with a specific tag (e.g., <p>, <div>) (returns an HTMLCollection).
Example let elements = document.getElementsByTagName("p");
4. Selecting Elements Using Query Selectors
Method document.querySelector(selector)
Description Selects the first element that matches a CSS selector.
Example let element = document.querySelector(".myClass");
Query Selector All
Method document.querySelectorAll(selector)
Description Selects all elements that match a CSS selector (returns a NodeList).
Example let elements = document.querySelectorAll("div.myClass");
5. Selecting Elements by Name
Method document.getElementsByName(name)
Description Selects elements with a specific name attribute (returns a NodeList).
Example let elements = document.getElementsByName("username");